package com.jcfk.system.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.jcfk.common.business.controller.BaseController;
import com.jcfk.common.business.enums.AvailableStatus;
import com.jcfk.common.business.log.annotation.RequestLogHeader;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.system.domain.dto.SysOrganizationDTO;
import com.jcfk.system.domain.po.SysUser;
import com.jcfk.system.domain.query.SysOrganizationQuery;
import com.jcfk.system.service.SysOrganizationService;
import com.jcfk.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 组织机构信息维护 服务接口
 *
 * @author 李炳海
 */
@Api(value = "/sysOrganization", tags = {"组织机构信息维护 服务接口"})
@RestController
@RequestMapping("/sysOrganization")
public class SysOrganizationController extends BaseController {
    /**
     * 多级分类服务
     */
    @Autowired
    private SysOrganizationService sysOrganizationService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 查询机构列表
     *
     * @param query
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "SysOrganizationQuery", name = "query", value = "", required = true)})
    @ApiOperation(value = "查询机构列表", notes = "查询机构列表", httpMethod = "POST")
    @PostMapping("getList")
    public RetResult<List<SysOrganizationDTO>> getList(@RequestBody SysOrganizationQuery query) {
        List<SysOrganizationDTO> list = sysOrganizationService.getList(query);
        List<String> userIds = new ArrayList<>();
        for (SysOrganizationDTO sysOrganizationDTO : list) {
            if (sysOrganizationDTO.getChargeManagerId() != null)
                userIds.add(sysOrganizationDTO.getChargeManagerId());
        }

        if (userIds.size() > 0) {
            List<SysUser> users = sysUserService.listByIds(userIds);
            Map<String, String> map = new HashMap<>();
            for (SysUser user : users) {
                map.put(user.getId(), user.getFirstName());
            }
            for (SysOrganizationDTO sysOrganizationDTO : list) {
                sysOrganizationDTO.setChargeManagerName(map.get(sysOrganizationDTO.getChargeManagerId()));
            }
        }

        return RetResult.ok(list);
    }

    /**
     * 根据id获取机构信息
     *
     * @param id
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "string", name = "id", value = "", required = true)})
    @ApiOperation(value = "根据id获取机构信息", notes = "根据id获取机构信息", httpMethod = "POST")
    @PostMapping("get/{id}")
    public RetResult<SysOrganizationDTO> get(@PathVariable(name = "id") String id) {
        if (StrUtil.isEmpty(id)) {
            throw new RuntimeException("主键不能为空");
        }
        SysOrganizationDTO dto = sysOrganizationService.get(id);
        if (!StringUtils.isEmpty(dto.getChargeManagerId())) {
            SysUser user = sysUserService.getById(dto.getChargeManagerId());
            dto.setChargeManagerName(user.getFirstName());
        }


        return RetResult.ok(dto);
    }

    /**
     * 根据id获取机构信息
     *
     * @param ids
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "string", name = "id", value = "", required = true)})
    @ApiOperation(value = "根据id获取机构信息", notes = "根据id获取机构信息", httpMethod = "POST")
    @PostMapping("get/list")
    public RetResult<?> get(@RequestBody List<String> ids) {
        if (ids == null || ids.size() == 0) {
            RetResult.ok(new ArrayList<>());
        }
        List<SysOrganizationDTO> sysOrganizationDTOS = convertList(sysOrganizationService.listByIds(ids), SysOrganizationDTO.class);

        List<String> userIds = new ArrayList<>();
        for (SysOrganizationDTO sysOrganizationDTO : sysOrganizationDTOS) {
            if (sysOrganizationDTO.getChargeManagerId() != null)
                userIds.add(sysOrganizationDTO.getChargeManagerId());
        }

        if (userIds.size() > 0) {
            List<SysUser> users = sysUserService.listByIds(userIds);
            Map<String, String> map = new HashMap<>();
            for (SysUser user : users) {
                map.put(user.getId(), user.getFirstName());
            }
            for (SysOrganizationDTO sysOrganizationDTO : sysOrganizationDTOS) {
                sysOrganizationDTO.setChargeManagerName(map.get(sysOrganizationDTO.getChargeManagerId()));
            }
        }

        return RetResult.ok(sysOrganizationDTOS);
    }

    /**
     * 保存机构
     *
     * @param multiLevelTree
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "SysOrganizationDTO", name = "multiLevelTree", value = "", required = true)})
    @ApiOperation(value = "保存机构", notes = "保存机构", httpMethod = "POST")
    @RequestLogHeader(modular = "组织机构", businessType = "保存")
    @PostMapping("/save")
    public RetResult<SysOrganizationDTO> save(@RequestBody SysOrganizationDTO multiLevelTree) {
        // 数据校验
        RetResult ret = sysOrganizationService.isValid(multiLevelTree);
        if (!ret.getCode().equals(RetResult.SUCCESS)) {
            return ret;
        }

        if (StrUtil.isEmpty(multiLevelTree.getId())) {
            // 新增
            return RetResult.ok(sysOrganizationService.insert(multiLevelTree));
        } else {
            // 更新
            return RetResult.ok(sysOrganizationService.update(multiLevelTree));
        }
    }

    /**
     * 删除列表(逻辑删除)
     *
     * @param dto
     * @return
     */
    @ApiImplicitParams({})
    @ApiOperation(value = "删除列表(逻辑删除)", notes = "删除列表(逻辑删除)", httpMethod = "POST")
    @RequestLogHeader(modular = "机构", businessType = "删除列表")
    @PostMapping("delete")
    public RetResult<?> delete(@RequestBody SysOrganizationDTO dto) {

        // 校验
        for (String id : dto.getIds()) {
            Boolean haveChild = sysOrganizationService.isHaveChild(id);
            if (haveChild.equals(true)) {
                return RetResult.fail("不能删除有下级机构的组织机构");
            }
        }
        sysOrganizationService.logicDeleteList(dto.getIds());
        return RetResult.ok();
    }

    /**
     * 批量物理删除(通过ids)
     *
     * @param ids
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "String[]", name = "ids", value = "", required = true)})
    @ApiOperation(value = "批量物理删除(通过ids)", notes = "批量物理删除(通过ids)", httpMethod = "POST")
    @RequestLogHeader(modular = "组织机构", businessType = "删除列表")
    @PostMapping("deleteByIds")
    public RetResult<?> deleteByIds(@RequestBody String[] ids) {
        return RetResult.ok(sysOrganizationService.deleteByIds(ids));
    }

    /**
     * 获取组织机构树
     *
     * @param query
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "SysOrganizationQuery", name = "query", value = "", required = true)})
    @ApiOperation(value = "获取组织机构树", notes = "获取组织机构树", httpMethod = "POST")
    @PostMapping("getTree")
    public RetResult<List<SysOrganizationDTO>> getTree(@RequestBody SysOrganizationQuery query) {
        return RetResult.ok(sysOrganizationService.getTree(query));
    }

    /**
     * 获取可用组织机构树
     *
     * @param query
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "SysOrganizationQuery", name = "query", value = "", required = true)})
    @ApiOperation(value = "获取可用组织机构树", notes = "获取可用组织机构树", httpMethod = "POST")
    @PostMapping("getUsableTree")
    public RetResult<List<SysOrganizationDTO>> getUsableMultiLevelTree(@RequestBody SysOrganizationQuery query) {
        query.setEnabled(Integer.parseInt(AvailableStatus.ENABLE.getCode()));
        return RetResult.ok(sysOrganizationService.getTree(query));
    }

    /**
     * 判断是否有下级组织机构
     *
     * @param id
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", dataType = "string", name = "id", value = "", required = true)})
    @ApiOperation(value = "判断是否有下级组织机构", notes = "判断是否有下级组织机构", httpMethod = "POST")
    @PostMapping("isHaveChild")
    public RetResult<?> isHaveChild(@RequestParam String id) {
        return RetResult.ok(sysOrganizationService.isHaveChild(id));
    }
}
